<template>
	<uni-popup ref="popup" @change="change" @maskClick="maskClick" :is-mask-click="false">
		<form @submit="submit">
			<view class="form">
				<view class="form-title">设备登录</view>
				<view class="form-item">
					<input placeholder="请输入设备账号" name="username" v-model="username" class="form-control" />
				</view>
				<view class="form-item">
					<input password placeholder="请输入设备密码" @input="setPassword" name="password" v-model="setpassword"
						class="form-control" />
				</view>
				<view class="form-item">
					<button type="primary" form-type="submit" style="width: auto">确认</button>
				</view>
			</view>
		</form>
	</uni-popup>
</template>

<script>
	import {
		XMMD5Encrypt
	} from "@/utils/md5Encrypt.js"
	export default {
		props: {
			device: {
				type: Object,
				value: () => {
					return {}
				}
			}
		},
		data() {
			return {
				username:'admin',
				password:'',
				setpassword:'',
				token:'',
				LoginToken:'',
				tryCount:0,
				deviceNo:'',
				tryTokenCount:0,
				tryTimeOutCount:0,
				tryFailCount:0
			}
		},
		watch: {
			device: {
				handler: function(res) {
					console.log('设备登录===========', res);
					this.token = res.token
					this.LoginToken = res.adminToken
					this.deviceNo = res.deviceNo
				},
				// immediate: true,
				deep: true
			}
		},
		destroyed() {
			console.log('退出登录页');
			uni.hideLoading()
		},
		methods:{
			open(){
				console.log('请输入设备密码=========================66666');
				this.$refs.popup.open('center')
			},
			close() {
				this.$refs.popup.close()
			},
			change(ev) {
				this.$emit('@change', ev)
			},
			maskClick() {
				// uni.navigateBack({
				// 	delta:1
				// })
			},
			setPassword(v) {
				console.log('密码', v.detail.value);
				this.password = XMMD5Encrypt(v.detail.value)
			},
			submit(ev) {
				console.log(this.token,'token')
				console.log(this.device,this.LoginToken,'LoginToken')
				console.log('登录参数====',arguments);
				if (arguments[0] && arguments[0].type === 'submit') {
					this.username = arguments[1] || this.username
					this.password = arguments[2] || this.password
					this.LoginToken = arguments[2] || this.LoginToken
				} else {
					this.username = arguments[0] || this.username
					this.password = arguments[1] || this.password
					this.LoginToken = arguments[2] || this.LoginToken
				}
				
				// if(!this.password && !this.LoginToken){
				// 	uni.showToast({
				// 		title: '请输入设备密码'
				// 	});
				// 	console.log('请输入设备密码=========================111');
				// 	this.open();
				// 	return
				// }
				if (this.username === '') {
					uni.showToast({
						title: '设备账号不能为空'
					});
					return;
				}
				let time = new Date()
				let time1 = time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()+':'+time.getMilliseconds()
				this.$logs({info: '开始请求登录接口',time:time1})
				let page = getCurrentPages()
				// if(page.length == 2){
				// 	uni.showLoading({
				// 		title: '登录中...',
				// 		mask: true
				// 	});
				// }
				let token = uni.getStorageSync('deviceToken') || this.token;
				let device = this.device
				let data = {
					encryptType: device.devPassWord?'DISABLE':'MD5', //MD5
					LoginType: 'DVRIP-Web',
					UserName: this.username,
					PassWord: this.password,
					Name: 'generalinfo',
					KeepaliveTime: 20
				};
				if (this.LoginToken) {
					data.LoginToken = this.LoginToken
					data.encryptType = 'TOKEN'
				}
				getApp().globalData.api.deviceLogin(data, token, (result) => {
					uni.hideLoading();
					this.$logs({
						apiUrl: '设备登录接口',
						sn:this.deviceNo,
						data:data,
						res: result.data
					})
					if (result.data.code === 2000) {
						let Ret = result.data.data.Ret
						// 登录成功 或 已登录
						if (result.data.data.Ret === 100 || result.data.data.Ret === 104) {
							this.close()
							this.$emit('submit', {
								username: this.username,
								password: this.password,
								twice:arguments[3] == 'twice'?true:false
							})
							this.tryTokenCount = 0
							this.tryCount = 0
							this.tryTimeOutCount = 0
							this.tryFailCount = 0
							this.$logs({apiUrl: '设备登录成功接口',data:result.data})
							if (arguments[3] == 'twice') {
								uni.$emit('twiceSubmitSuccess')
							}
						} else if(result.data.data.Ret === 137){
							this.tryTokenCount ++
							if(this.tryTokenCount == 1){
								this.getAdminToken()
							}else if(this.tryTokenCount == 2){
								setTimeout(()=>{
									this.getAdminToken()
								},5000)
							}else if(this.tryTokenCount == 3){
								setTimeout(()=>{
									this.getAdminToken()
								},15000)
							}else{
								if(page.length ==2){
									uni.showToast({
										title:getApp().globalData.errCodeMsg.RetCodeMsg[result.data.data.Ret]||result.data.data.RetMsg,
										icon:"none"
									})
								}
							}
							this.$logs({apiUrl: '设备登录接口',data:data,result:result.data},'error')
						}
						// 出错
						else {
							if(page.length ==2){
								uni.showToast({
									title: getApp().globalData.errCodeMsg.RetCodeMsg[result.data.data.Ret] ||
										result.data.data.RetMsg,
									icon: "none"
								})
							}
							this.open()
							this.$logs({apiUrl: '设备登录接口',data:data,result:result.data},'error')
						}
					}
					// 4000 参数错误
					else if (result.data.code === 4000) {
						if(page.length ==2){
							uni.showToast({
								title: result.data.msg,
								icon: 'none',
								success: (res) => {
									this.getDeviceToken([this.device.deviceNo])
								}
							});
						}
						this.$logs({apiUrl: '设备登录接口',data:data,result:result.data},'error')
					}
					// 4100 非法请求，设备未登录或录像失败
					else if (result.data.code === 4100) {
						if(page.length ==2){
							uni.showToast({
								title: result.data.msg,
								icon: 'none',
								success: (res) => {
									console.log('请输入设备密码=========================3333');
									this.open()
								}
							});
						}
						this.$logs({apiUrl: '设备登录接口4100',data:data,result:result.data},'error')
					}
					// 4103 低功耗设备唤醒失败  重试一次
					else if(result.data.code == 4103){
						this.tryCount ++
						if(this.tryCount == 1){
							this.submit()
						}
						this.$logs({apiUrl: '设备登录接口4103',data:data,result:result.data},'error')
					}
					// 4118连接超时  重试三次
					else if(result.data.code == 4118){
						this.tryTimeOutCount ++
						if(this.tryTimeOutCount < 4){
							this.submit()
						}else{
							if(page.length ==2){
								uni.showToast({
									title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
									icon: 'none',
								});
							}
						}
						this.$logs({apiUrl: '设备登录接口超时4118',data:data,result:result.data},'error')
					}
					 // 4120 设备进入深度休眠
					else if(result.data.code == 4120){
						if(page[page.length - 1].$page.fullPath.includes('live-lexin') || page[page.length - 1].$page.fullPath.includes('live1')){
							uni.showModal({
								content:'设备已进入深度休眠状态，请手动唤醒后继续访问设备',
								showCancel:false,
								confirmColor:'#FF0025',
								confirmText:'确定',
								success: (res) => {
									uni.navigateBack({})
								}
							})
						}
						this.$logs({apiUrl: '设备登录接口超时4120',data:data,result:result.data},'error')
					}
					// 其他情况
					else {
						if(page.length ==2){
							uni.showToast({
								title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result
									.data.msg,
								icon: 'none',
							});
						}
						this.$logs({apiUrl: '设备登录接口',data:data,result:result.data},'error')
					}
				},(err)=>{
					this.tryFailCount++
					if(this.tryFailCount == 1){
						this.submit()
					}
					console.log('设备登录接口请求失败===',err);
					this.$logs({apiUrl: '设备登录接口请求失败',data:data,result:result.data},'error')
				});
			},
			// 获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {

					this.deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.sn) {
								item.token = pro.token;
							}
						});
					});
					let tokenList = [];
					result.forEach((item) => {
						tokenList.push(item.token);
					});
			 	this.getDeviceStatus(tokenList, this.deviceList);
				});
			},

			// 获取设备状态
			getDeviceStatus(tokenList, deviceList) {
				const data = {
					token: tokenList
				};
			 getApp().globalData.api.getDeviceStatus(data, (result) => {
					deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.uuid) {
								this.$set(item, 'status', pro)
							}
						});
					});

					let bossDeviceList = uni.getStorageSync('bossDeviceList')
					bossDeviceList.forEach(item => {
						deviceList.forEach(pro => {
							if (item.deviceNo === pro.deviceNo) {
								item.token = pro.token
								item.status = pro.status
							}
						})
					})

					uni.setStorageSync('deviceList', deviceList)
					uni.setStorageSync('bossDeviceList', bossDeviceList)
					console.log('请输入设备密码=========================55555');
					this.open()

				});
			},
			// 获取设备最新的adminToken
			getAdminToken(){
				let data = {
					deviceNo:this.deviceNo,
					isLatest:true
				}
				getApp().globalData.api.getDeviceTokenLocal(data, (result) => {
					this.adminToken = result.adminToken
					this.submit()
				});
			}
		}
	}
</script>

<style>
	.form {
		background: white;
		padding: 60rpx;
		border-radius: 10rpx;
	}

	.form .form-item {
		margin-top: 20rpx;
	}

	.form .form-title {
		text-align: center;
		margin-bottom: 40rpx;
		font-weight: bold;
	}

	.form .form-item .form-control {
		background: #efefef;
	}
</style>
